package com.rf.richfitwheel.admin.sys.controller;

import cn.avicnet.apigw.client.sdk.SignatureAuth;
import cn.avicnet.apigw.client.sdk.SignatureAuthConfig;
import cn.avicnet.apigw.client.sdk.SignatureAuthFactory;
import cn.avicnet.apigw.client.sdk.constant.ApiGwEnum;
import cn.com.infosec.netsign.agent.NetSignAgent;
import cn.com.infosec.netsign.agent.NetSignResult;
import cn.hutool.json.JSONUtil;
import com.alibaba.csb.sdk.HttpCaller;
import com.alibaba.csb.sdk.HttpCallerException;
import com.alibaba.csb.sdk.HttpParameters;
import com.alibaba.csb.sdk.HttpReturn;
import com.rf.richfitwheel.admin.annotation.ModifyAnnotaionFactory;
import com.rf.richfitwheel.admin.annotation.UserOperateLog;
import com.rf.richfitwheel.admin.conf.AppAccess;
import com.rf.richfitwheel.admin.conf.CommonPropertiesConfig;
import com.rf.richfitwheel.admin.conf.IamPropertiesConfig;
import com.rf.richfitwheel.admin.contants.CustomToken;
import com.rf.richfitwheel.admin.contants.UrlConstant;
import com.rf.richfitwheel.admin.iam.HttpEntityJsonUtil;
import com.rf.richfitwheel.admin.iam.model.TicketVerifyResult;
import com.rf.richfitwheel.admin.shiro.PasswordExpired;
import com.rf.richfitwheel.admin.sys.model.SysLoginForm;
import com.rf.richfitwheel.admin.sys.model.User;
import com.rf.richfitwheel.admin.sys.service.SysCaptchaService;
import com.rf.richfitwheel.admin.sys.service.SysUserAuthService;
import com.rf.richfitwheel.admin.sys.service.SysUserService;
import com.rf.richfitwheel.admin.sys.service.TenantService;
import com.rf.richfitwheel.admin.sys.vo.UserVO;
import com.rf.richfitwheel.admin.utils.PasswordHelper;
import com.rf.richfitwheel.admin.utils.UserUtil;
import com.rf.richfitwheel.common.contants.CommonServiceError;
import com.rf.richfitwheel.common.contants.Constant;
import com.rf.richfitwheel.common.utils.DateUtils;
import com.rf.richfitwheel.common.utils.R;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URI;
import java.util.*;

/**
 * 登录相关
 *
 * @author hushouquan
 * @date 2018-11-24
 */
@RestController
@RequestMapping(UrlConstant.WEB_ADMIN_URL + "/login")
public class SysLoginController {

    private static Logger log = LoggerFactory.getLogger(SysLoginController.class);
    @Value("${spring.profiles.active}")
    private String springProfilesActive;

    @Autowired
	private SysUserService sysUserService;
    @Autowired
    private SysCaptchaService sysCaptchaService;

    @Autowired
    private PasswordExpired passwordExpired;

    @Autowired
    private CommonPropertiesConfig commonPropertiesConfig;
    
    @Autowired
    private IamPropertiesConfig iamPropertiesConfig;
    
    @Autowired
    private RestTemplate restTemplateOuter;

    @Autowired
    private SysUserAuthService sysUserAuthService;
    @Autowired
    private TenantService tenantService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 获取验证码
     *
     * @throws Exception
     */
    @GetMapping("/captcha.jpg")
    public void captcha(HttpServletResponse response, String uuid) throws Exception {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/png");

        //获取图片验证码
        BufferedImage image = sysCaptchaService.getCaptcha(uuid);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "png", out);
        IOUtils.closeQuietly(out);
    }

    /**
     * 登录
     */
    @PostMapping("/login")
    @UserOperateLog(module = "系统功能", methods = "login", description = "系统登录")
    public Map<String, Object> login(@RequestBody SysLoginForm form, HttpServletRequest request, HttpServletResponse response) throws IOException {
       /* 压力测试暂时注掉验证码*/
       boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
        if(!captcha){
            return R.error("验证码不正确");
        }
        if (StringUtils.isEmpty(form.getTerminal())) {
            return R.error("请传入终端类型");
        }
        String tenantCode = form.getTenantId();
        if (StringUtils.isEmpty(tenantCode)) {
            return R.error("租户编号不正确");
        }
        String tenantId = tenantService.getTenantIdByCode(tenantCode);
        if (StringUtils.isEmpty(tenantId)) {
            return R.error("租户编号不正确");
        }
        form.setTenantId(tenantId);
        //用户信息
//		User user = sysUserService.queryByUserName(form.getUsername());
        // 想要得到 SecurityUtils.getSubject()　的对象．．访问地址必须跟shiro的拦截地址内．不然后会报空指针
        Subject subject = SecurityUtils.getSubject();
        // 用户输入的账号和密码,,存到UsernamePasswordToken对象中..然后由shiro内部认证对比,
        // 认证执行者交由ShiroDbRealm中doGetAuthenticationInfo处理
        // 当以上认证成功后会向下执行,认证失败会抛出异常
        CustomToken token = new CustomToken(form.getUsername(), form.getPassword(), form.getTenantId());
        try {
            token.setTerminal(form.getTerminal());
            //通过Shiro进行用户名密码验证
            subject.login(token);

            //将用户登陆信息保存到数据库
            Session session = SecurityUtils.getSubject().getSession();
            //更新最后登录时间
            User user = (User) session.getAttribute(Constant.USERSESSION);
            ModifyAnnotaionFactory.newInstance().ModifyAnnotation(getClass(), UserOperateLog.class, "login", "bussid", user.getId(), form.getClass(), HttpServletRequest.class, HttpServletResponse.class);

            //上次登录时间
            User userUpdate = new User();
//			BeanUtils.copyProperties(user, userUpdate);
            userUpdate.setId(user.getId());
            userUpdate.setLoginTime(new Date());
            userUpdate.setLoginTerminal(form.getTerminal());
            sysUserAuthService.update(userUpdate);
            Date lcpt = user.getLastChangedPwdTime();
            int days = DateUtils.compareToDays(new Date(), lcpt);
            if(user.getLastChangedPwdTime() == null){
                //首次登录强制更改密码
                return R.error(975, "您的密码为系统初始化密码，请您修改密码！");
            }
            if (passwordExpired.getDays() - days < passwordExpired.getAlarm()) {
                if (passwordExpired.isForcechangepwd() && passwordExpired.getDays() - days < passwordExpired.getForcedays()) {
                    return R.error(976, "您的密码已过期，请您修改密码！");
                }
                return R.error(977, "您的密码即将过期，请您尽快修改密码。如到期未修改账户将被停用！");
            }
            return R.ok();//.put("token", token);
        } catch (UnknownAccountException uae) {
            token.clear();
//            return R.error("用户未找到");//用户未找到
            log.warn("用户未找到：" + form.getUsername(), uae);
            return R.error("用户名或密码错误");//等保3级要求提示模棱两可一点
        } catch (IncorrectCredentialsException ice) {
            token.clear();
            log.warn("密码错误：" + form.getUsername(), ice);
//            return R.error("密码错误");//密码错误
            return R.error("用户名或密码错误");//等保3级要求提示模棱两可一点
        } catch (LockedAccountException lae) {
            token.clear();
            return R.error("用户已经被锁定");//用户已经被锁定,不能登录
        } catch (ExcessiveAttemptsException e) {
            token.clear();
            return R.error("登录失败次数过多");//登录失败次数过多
        } catch (DisabledAccountException e) {
            token.clear();
            return R.error("账户已被禁用");//账户已被禁用
        } catch (Exception e) {
            token.clear();
            e.printStackTrace();
            return R.error("登录失败");//登录失败
        }
    }

    /**
     * 统一身份认证登录接口
     *
     * @param iamInfo {"iamCode":身份认证返回的code, "terminal":终端类型({@link Constant.TerminalType}
     * @return
     * @throws IOException
     */
    @PostMapping("/iamLogin")
    @UserOperateLog(module = "系统功能", methods = "iamLogin", description = "通过统一身份认证登录系统", functionNo = "101055")
    public R iamLogin(@RequestBody Map<String, String> iamInfo, HttpServletRequest request, HttpServletResponse response) throws Exception {
        CustomToken token = new CustomToken();
        try {
            String ticket = iamInfo.get("ticket");
            if(StringUtils.isEmpty(ticket)){
                return R.error("请传入票据");
            }
            if(!iamInfo.containsKey("terminal")) {
                return R.error("请传入终端类型");
            }
            if (StringUtils.isEmpty(iamInfo.get("terminal"))) {
                return R.error("请传入终端类型");
            }
            String tenantCode = iamInfo.get("tenantId");
            if (StringUtils.isEmpty(tenantCode)) {
                return R.error("租户编号不正确");
            }
            String tenantId = tenantService.getTenantIdByCode(tenantCode);
            if (StringUtils.isEmpty(tenantId)) {
                return R.error("租户编号不正确");
            }
            String moduleType = request.getHeader("moduleType") == null ? request.getHeader("Moduletype") : request.getHeader("moduleType"); //从请求头获取模块类型，如果有值就查对应模块菜单
            AppAccess appAccess = iamPropertiesConfig.getAppAccess().stream().filter(m -> m.getModuleType().contains(moduleType)).findFirst().get();
            String service = iamInfo.get("service") == null ? appAccess.getFrontUrl() : iamInfo.get("service");
            TicketVerifyResult ticketVerifyResult = executeTicketVerify(appAccess, service, ticket);
//            TicketVerifyResult ticketVerifyResult = verifySSOTicket(service, ticket);
            if(ticketVerifyResult == null || ticketVerifyResult.getServiceResponse() == null || ticketVerifyResult.getServiceResponse().getAuthenticationSuccess() == null){
                log.error("通过票据获取用户信息失败{}", ticketVerifyResult);
                return R.error("通过票据获取用户信息失败");
            }
//            log.info("ticketVerifyResult" + ticketVerifyResult);
            String userId = ticketVerifyResult.getServiceResponse().getAuthenticationSuccess().getUser();
            if(userId == null){
                log.error("通过票据获取用户信息失败:userId为空");
                return R.error("通过票据获取用户信息失败");
            }
            User user = sysUserService.selectByAccount(userId);
            if(user == null){
                user = sysUserService.selectByAccount(ticketVerifyResult.getServiceResponse().getAuthenticationSuccess().getAttributes().getUid());
            }
            if (user == null) {
                log.info("票据验证接口返回值{}", ticketVerifyResult.getServiceResponse());
                return R.error("系统中不存在该用户，请先联系管理员添加用户！");
            }
            if (Constant.USER_STATUS_DELETED.equals(user.getStatus())) {
                log.info("业务系统中用户为删除状态{}", userId);
                return R.error("系统中不存在该用户，请先联系管理员添加用户！");
            }
            if (Constant.USER_STATUS_LOCKED.equals(user.getStatus())) {
                return R.error("用户已被锁定，请联系管理员解锁！");
            }
            if (Constant.USER_STATUS_DISABLED.equals(user.getStatus())) {
                return R.error("用户已被禁用，请联系管理员启用！");
            }
            //第三步，终于可以登录了,在这儿免密登录创建会话
            token = new CustomToken(user.getUsername(), false, tenantCode);
            token.setTerminal(iamInfo.get("terminal"));
            //通过Shiro登录
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            //这个是记操作日志的
//            ModifyAnnotaionFactory.newInstance().ModifyAnnotation(getClass(), UserOperateLog.class, "iamLogin", "bussid", user.getId(), iamInfo.getClass(), HttpServletRequest.class, HttpServletResponse.class);
            //上次登录时间
            User userUpdate = new User();
            userUpdate.setId(user.getId());
            userUpdate.setLoginTime(new Date());
            userUpdate.setLoginTerminal(iamInfo.get("terminal"));
            sysUserAuthService.update(userUpdate);
            return R.ok();
        } catch (RestClientException re) {
            log.error(re.getMessage(), re);
            return R.error("通过票据获取用户信息失败");//
        } catch (UnknownAccountException uae) {
            if (token != null) {
                token.clear();
            }
            return R.error("用户未找到");//用户未找到
        } catch (IncorrectCredentialsException ice) {
            if (token != null) {
                token.clear();
            }
            return R.error("密码错误");//密码错误
        } catch (LockedAccountException lae) {
            if (token != null) {
                token.clear();
            }
            return R.error("用户已经被锁定");//用户已经被锁定,不能登录
        } catch (ExcessiveAttemptsException e) {
            if (token != null) {
                token.clear();
            }
            return R.error("登录失败次数过多");//登录失败次数过多
        } catch (DisabledAccountException e) {
            if (token != null) {
                token.clear();
            }
            return R.error("账户已被禁用");//账户已被禁用
        } catch (Exception e) {
            if (token != null) {
                token.clear();
            }
            log.error("通过统一身份认证登录失败", e);
            return R.error("登录失败");//登录失败
        }
    }
    
    /**
     * 调用门户接口获取票据对应用户
     * @param appAccess 门户接口相关配置
     * @param service service
     * @param ticket 票据
     * @return 认证结果
     * @throws Exception 异常
     */
    private TicketVerifyResult executeTicketVerify(AppAccess appAccess, String service, String ticket) throws Exception{
        SignatureAuthConfig signatureAuthConfig = new SignatureAuthConfig();
        signatureAuthConfig.setApiGw(ApiGwEnum.APACHE_APISIX);
        signatureAuthConfig.setAccessKey(appAccess.getAccessKey());
        signatureAuthConfig.setSecretKey(appAccess.getSecretKey());
        SignatureAuth signatureAuth = SignatureAuthFactory.createSignatureAuth(signatureAuthConfig);
        try {
            URI uri = new URIBuilder(iamPropertiesConfig.getUrl() + UrlConstant.IAM_API_VERIFY_URL)
                    .addParameter("service", service)
                    .addParameter("format", "json")
                    .addParameter("ticket", ticket)
                    .build();
            HttpUriRequest httpUriRequest = signatureAuth.createHttpUriRequestBodySign(uri,
                    "GET", null, new HashMap<>());
            CloseableHttpClient httpClient = HttpEntityJsonUtil.getHttpsClient(iamPropertiesConfig.getUrl().contains("https"));
            CloseableHttpResponse response = httpClient.execute(httpUriRequest);
            int statusCode = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            if(statusCode == org.apache.http.HttpStatus.SC_OK){
                return HttpEntityJsonUtil.httpEntityContentToJsonArray(entity, TicketVerifyResult.class);
            }else{
                log.warn("通过票据获取用户信息失败:{}", EntityUtils.toString(entity));
                return null;
            }
        } catch (Exception e) {
            throw e;
        }
    }
    
    /**
     * 调用商网的接口获取票据对应用户
     * @param service 业务服务
     * @param ticket 票据
     * @return 用户信息
     */
    private TicketVerifyResult verifySSOTicket(String service, String ticket){
        HttpParameters.Builder builder = HttpParameters.newBuilder();
        builder.requestURL(iamPropertiesConfig.getCsbUrl() + UrlConstant.IAM_API_VERIFY_ROOT)
                .api(UrlConstant.IAM_API_VERIFY_TICKET)
                .version("1.0.0")
                .method("get")
                .contentType("application/json;charset=utf-8");
        builder.putParamsMap("format", "json");
        builder.putParamsMap("service", service);
        builder.putParamsMap("ticket", ticket);
        try {
            HttpReturn res = HttpCaller.invokeReturn(builder.build());
            // 在 res 里获取相关的信息
//            System.out.println(res.httpCode + "::::::" + res.getResponseStr());
            return JSONUtil.toBean(res.getResponseStr(), TicketVerifyResult.class); // 转对象
        } catch (HttpCallerException e) {
            throw new RuntimeException("验证票据" + ticket + "失败", e);
        }
    }
    
    
    /**
     * 财金云登录接口
     * @param iamInfo {"iamCode":身份认证返回的code, "terminal":终端类型({@link Constant.TerminalType}
     * @return
     * @throws IOException
     */
	@PostMapping("/appLogin")
	public R appLogin(@RequestBody Map<String, String> iamInfo, HttpServletRequest request, HttpServletResponse response)throws Exception {
		CustomToken token = new CustomToken();
		try {
		    String username = iamInfo.get("username");
            String apptoken = iamInfo.get("token");
            String terminal = iamInfo.get("terminal");
            if (null != username) {
                String appid = "0001";
                //dcb16caa76074644b8f06f38f675d117
                String secrect = "dcb16caa76074644b8f06f38f675d117";
                String tokenFormate = "appid=%susername=%ssecrect=%s";
                String tokenStr = String.format(tokenFormate, appid, username, secrect);

                //两次加密
                String currenttoken = DigestUtils.md5DigestAsHex(tokenStr.getBytes());
                currenttoken = DigestUtils.md5DigestAsHex(currenttoken.getBytes());

                //判断财金云令牌是否正确
                if (currenttoken.equals(apptoken)) {
                    User user = new User();
                    user.setUsername(username);
                    List<User> userList = sysUserAuthService.getUser(user);
                    if (userList.size() == 0) {
                        return R.error("司库系统中不存在该用户，请先联系管理员添加用户！");
                    }
                    User u = userList.get(0);
                    if (Constant.USER_STATUS_DELETED.equals(u.getStatus())) {
                        return R.error("司库系统中不存在该用户，请先联系管理员添加用户！");
                    }
                    if (Constant.USER_STATUS_LOCKED.equals(u.getStatus())) {
                        return R.error("用户已被锁定，请联系管理员解锁！");
                    }
                    if (Constant.USER_STATUS_DISABLED.equals(u.getStatus())) {
                        return R.error("用户已被禁用，请联系管理员启用！");
                    }
                    //第三步，终于可以登录了,在这儿免密登录创建会话
                    token = new CustomToken(u.getUsername());
                    token.setTerminal(terminal);
                    //通过Shiro登录
                    Subject subject = SecurityUtils.getSubject();
                    subject.login(token);
                    return R.ok();
                } else {
                    return R.error("令牌错误");
                }

            } else {
                throw  new UnknownAccountException();
            }
		} catch(UnknownAccountException uae){
			if(token != null){
				token.clear();
			}
			return R.error("用户未找到");//用户未找到
		} catch(IncorrectCredentialsException ice){
			if(token != null){
				token.clear();
			}
			return R.error("密码错误");//密码错误
		}catch (LockedAccountException lae) {
			if(token != null){
				token.clear();
			}
			return R.error("用户已经被锁定");//用户已经被锁定,不能登录
		} catch (ExcessiveAttemptsException e) {
			if(token != null){
				token.clear();
			}
			return R.error("登录失败次数过多");//登录失败次数过多
		} catch (DisabledAccountException e) {
			if(token != null){
				token.clear();
			}
			return R.error("账户已被禁用");//账户已被禁用
		}catch (Exception e){
			if(token != null){
				token.clear();
			}
			log.error("财金云登录失败", e);
			return R.error("登录失败");//登录失败
		}
	}

    /**
     * 退出
     */
    @UserOperateLog(module = "系统功能", methods = "logout", description = "退出登录")
    @PostMapping("/logout")
    public Map<String, Object> logout() {
        Map<String, Object> map = new HashMap<String, Object>();
        //sysUserTokenService.logout(getUserId());
        UserVO userVO = UserUtil.getUser();
        if (ObjectUtils.isEmpty(userVO)) {
            return R.ok();
        }
        //删除缓存中的机构数据
//        redisTemplate.delete(Constant.REDIS_PREFIX + userVO.getId());

        ModifyAnnotaionFactory.newInstance().ModifyAnnotation(getClass(), UserOperateLog.class, "logout", "bussid", userVO.getId());
        Subject subject = SecurityUtils.getSubject();
        subject.logout();//shiro退出
//		ResponseEntity<JSONObject> userinfoResponse = restTemplateOuter.getForEntity(commonPropertiesConfig.getIamUrl() + UrlConstant.IAM_USERINFO_URL  + "?appcode=" + commonPropertiesConfig.getIamAppcode() + "&secret=" + commonPropertiesConfig.getIamSecret() + "&token=" + tokenObj.getString("accessToken"), JSONObject.class);
//		R r =new R();
        return R.ok();
    }

    @GetMapping("/unauth")
    public R unauth() {
        return R.error(HttpStatus.SC_UNAUTHORIZED, "没有权限，请登录！");
    }

    /**
     * 解锁密码验证
     *
     * @param form     密码参数
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/unblock")
    public R unblock(@RequestBody SysLoginForm form, HttpServletRequest request, HttpServletResponse response) {
        try {
            UserVO userVO = UserUtil.getUser();
            //老密码
            String oldPassword = userVO.getPassword();
            userVO.setPassword(form.getPassword());
            userVO = PasswordHelper.encryptPassword(userVO);
            if (userVO.getPassword().equals(oldPassword)) {
                return R.ok();
            } else {
                return R.error("密码不正确！");
            }
        } catch (Exception e) {
            log.error(CommonServiceError.SERVICE_SYSTEM_EXCEPTION.getMsg(), e);
            return R.error(CommonServiceError.SERVICE_SYSTEM_EXCEPTION.getMsg());
        }
    }

    /**
     * 随便调用个方法续订下session
     *
     * @return
     */
    @GetMapping("/restSessionTime")
    public R restSessionTime() {
        return R.ok().put("res", "续订会话成功");
    }

    private ResourceBundle getResourceBundle(String baseName){
        return ResourceBundle.getBundle(baseName + "-" + getSpringProfilesActive());
    }

    public void setSpringProfilesActive(String springProfilesActive) {
        this.springProfilesActive = springProfilesActive;
    }

    public String getSpringProfilesActive() {
        return springProfilesActive;
    }
    
    /**
     * 验证证书并返回账号
     * @param param {signDataValue:""} 证书签名数据
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @PostMapping("/ukeyCheckSign")
    @UserOperateLog(module = "系统功能", methods = "ukeyCheckSign", description = "验证ukey证书")
    public Map<String, Object> ukeyCheckSign(@RequestBody Map<String, Object> param, HttpServletRequest request, HttpServletResponse response) throws IOException {
        try{
//            String headerDn = request.getHeader("headerDn");
            String signDataValue = param.get("signDataValue") == null ? null : param.get("signDataValue").toString();
//            log.info("checkSign--->headerDn=[{}]",headerDn);
//            log.info("checkSign--->signDataValue=[{}]",signDataValue);
            String plainText = "avic";
            NetSignResult result = null;
            //验证签名
            NetSignAgent.initialize(getResourceBundle("netsignagent"));
            result = NetSignAgent.attachedVerify(signDataValue, null, true);
            Integer resultNum = Integer.parseInt(result.getStringResult(NetSignResult.RESULT_NUMBER));
            if(resultNum != 1){
                return R.error(result.getStringResult(NetSignResult.RESULT_MSG));
            }
            String originData = new String(result.getByteArrayResult(NetSignResult.PLAIN_TEXT),"UTF-8");
            if (!plainText.equals(originData)) {
                //数据被篡改
                return R.error("数据被篡改");
            }
            String certDN = result.getStringResult(NetSignResult.SIGN_SUBJECT);//待验证的证书DN号域
            String certSN = result.getStringResult(NetSignResult.SIGN_SER_NUMBER);//待验证的证书SN号域
            //验证DN
            String[] strs = certDN.split("@");
//            log.info("checkSign--->strs=[{}]", Jacksons.parse(strs));
            //获取客户编号和用户编号
            String num = strs[strs.length - 1];
            String customerId = "CB1" + num.substring(0, 7);
            String userId = num.substring(7);
//            log.info("checkSign--->查询入参customerId=[{}],userId=[{}]", customerId,userId);
            /*AvicCbCertInf avicCbCertInf = avicCbCertInfService.getCertInfo(customerId, userId);
//            log.info("checkSign--->resultMap=[{}]", Jacksons.parse(avicCbCertInf));
            if(avicCbCertInf == null){
                //未查询到证书
                log.error("未查询到证书->{}{}", customerId,userId);
                return R.error("未查询到证书");
            }
            String stt = avicCbCertInf.getCciStt();
            String recstt = avicCbCertInf.getCciRecestt();
            if(!"2".equals(recstt)){
                //Ukey尚未签收
                log.error("Ukey尚未签收->{}{}", customerId,userId);
                return R.error("Ukey尚未签收");
            }
            if (!"1".equals(stt)) {
                //证书状态不正常
                log.error("证书状态不正常->{}{}", customerId,userId);
                return R.error("证书状态不正常");
            }
            AvicCbUserInf avicCbUserInf = avicCbUserInfService.getUserInfo(userId);
            if(avicCbUserInf == null) {
                return R.error("无法从证书解析用户");
            }
            return R.ok().put("username", avicCbUserInf == null ? "" : avicCbUserInf.getUifChannelcharid());//返回账号给前端进行登陆
            */
            return R.ok();
        } catch (Exception e) {
            log.error("证书验证失败",e);
            return R.error("证书验证失败");
        }
    }
}
